package com.chaos.auth.config.userdetails.service;

import cn.hutool.core.util.ObjectUtil;
import com.chaos.auth.config.grant.converter.helper.OAuth2EndpointHelper;
import com.chaos.auth.config.userdetails.details.AppUserDetails;
import com.chaos.auth.config.userdetails.service.base.UserDetailsExtService;
import com.chaos.framework.model.dto.result.data.DataResult;
import com.chaos.framework.model.dto.result.list.ListResult;
import com.chaos.framework.model.enums.ResultEnum;
import com.chaos.framework.starter.helper.CheckHelper;
import com.chaos.system.api.data.TUserData;
import com.chaos.system.api.feign.UserFeign;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Jacky
 */
@Slf4j
@Component
public class AppByPhoneDetailsService implements UserDetailsExtService {

    @Resource
    private UserFeign userFeign;

    @Override
    public UserDetails loadUserByPhone(String phone, Long tenantId) {
        TUserData queryData = TUserData.builder().phone(phone).build();
        //queryData.setTenantId(tenantId);
        ListResult<TUserData> userInfoDatasRes = userFeign.list(queryData);
        CheckHelper.requireSuccess(userInfoDatasRes);
        List<TUserData> userInfoDatas = userInfoDatasRes.getList();
        TUserData userData = null;
        if (ObjectUtil.isEmpty(userInfoDatas)) {
            DataResult<TUserData> userDataRes = userFeign.register(userData);
            CheckHelper.requireSuccess(userDataRes);
            userData = userDataRes.getData();
        }
        else {
            userData = userInfoDatas.get(0);
        }
        AppUserDetails userDetails = new AppUserDetails(userData);
        if (!userDetails.isEnabled()) {
            OAuth2EndpointHelper.throwError(ResultEnum.ACCOUNT_IS_NOT_ENABLED);
        }
        return userDetails;

    }


}
